﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Threading;
using System.Web.Http.Controllers;
using App.Core.Cache;
using System.Web.Mvc;

namespace App.Web.Filter
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class AuthorizeForWebApiAttribute:System.Web.Http.AuthorizeAttribute
    {   
        public string Auths { get; set; }
        readonly IUserCacheManager iUserCacheManager;
        public AuthorizeForWebApiAttribute()
        {
            this.iUserCacheManager = DependencyResolver.Current.GetService<IUserCacheManager>();
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (!String.IsNullOrEmpty(this.Auths))
            {
                string[] moduleAuthArr = this.Auths.Split(';');
                IDictionary<string, string> userModuleAuthMap = this.iUserCacheManager.GetAllModuleAuths();
                if (userModuleAuthMap == null)
                {
                    this.HandleUnauthorizedRequest(actionContext);
                }
                foreach (var moduleAuthItem in moduleAuthArr)
                {
                    if (String.IsNullOrEmpty(moduleAuthItem) || moduleAuthItem.Length < 2)
                        continue;
                    string[] moduleAuthSplit = moduleAuthItem.Split('=');
                    if (moduleAuthSplit.Length < 2)
                        continue;
                    string module = moduleAuthSplit[0];
                    if (!userModuleAuthMap.ContainsKey(module))
                        continue;
                    string[] auths = moduleAuthSplit[1].Split(',');
                    string[] authSelected = userModuleAuthMap[module].Split(',');

                    foreach (var authItem in auths)
                    {
                        if (authSelected.Any(x => x.Equals(authItem, StringComparison.OrdinalIgnoreCase)))
                        {
                            return;
                        }
                    }
                }
                this.HandleUnauthorizedRequest(actionContext);
            }

            base.OnAuthorization(actionContext);
        } 
    }
}